//
//  M3UserDefaults.m
// 
//
//  Created by 徐盟 on 2023/6/16.
//

#import "M3UserDefaults.h"

@interface M3UserDefaults()


@end

@implementation M3UserDefaults


-(instancetype) init
{
    if(self == [super init]){
      
    }
    
    return self;
}


     

+ (instancetype)share
{
    static M3UserDefaults *share = nil;
    static dispatch_once_t oneToken;
    dispatch_once(&oneToken, ^{
        share = [[M3UserDefaults alloc]init];
    });
    return share;
}
- (NSUserDefaults *)userDefaults
{
    if(!_userDefaults){
        _userDefaults = [NSUserDefaults standardUserDefaults];
    }
    
    return  _userDefaults;
}

@synthesize planLog = _planLog;

@synthesize keepLiveMode = _keepLiveMode;

- (NSInteger)keepLiveMode{
    if(_keepLiveMode == 0){
        NSInteger mode = [self.userDefaults integerForKey: M3UserDefaults_KEY_keepLivemode];
        _keepLiveMode = mode;
    }
    if(_keepLiveMode == 0){
        _keepLiveMode = KeepLiveService_Mode_Location;
    }
    
    return _keepLiveMode;
}

- (void)setKeepLivemode:(NSInteger)keepLivemode
{
    _keepLiveMode = keepLivemode;
    [self.userDefaults setValue:@(keepLivemode) forKey:M3UserDefaults_KEY_keepLivemode];
}


- (NSDictionary*)planLog
{
    
    if(_planLog == nil){
                
        
        NSString* jsonString  =  [self.userDefaults stringForKey:M3UserDefaults_KEY_planLog];

        if(jsonString != nil){
            NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
            NSError *error = nil;
            NSDictionary *data = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
            if(data != nil){
                _planLog = [NSDictionary dictionaryWithDictionary:data];
            }

        }
        
    }
    
    [XMLogger log:@"get planLog %@", [_planLog mj_JSONString]];
    
    return _planLog;
}


- (void)setPlanLog:(NSDictionary*)value
{
    if(value == nil){
        _planLog = nil;
        [self.userDefaults removeObjectForKey:M3UserDefaults_KEY_planLog];
    }else{
        _planLog = [NSDictionary dictionaryWithDictionary:value];
        
        NSString*  jsonString = [value mj_JSONString];


        [self.userDefaults setValue:jsonString forKey:M3UserDefaults_KEY_planLog];
        [self.userDefaults synchronize];
        
    }
    
    [XMLogger log:@"setPlanLog after %@", [_planLog mj_JSONString]];
}







@end

